package com.service.impl;

import com.fegin.InventoryFeign;
import com.jpa.OrderRepository;
import com.model.Order;
import com.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.core.model.BranchType;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @description:
 * @author: sksun2
 * @create: 2023-07-24
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private InventoryFeign inventoryFeign;

    @Override
    @GlobalTransactional(rollbackFor = {Exception.class},timeoutMills=Integer.MAX_VALUE)
//    @Transactional
    public String createOrder(String userId, String itemId, Integer num) {

        final String xid = RootContext.getXID();
        final BranchType branchType = RootContext.getBranchType();
        System.out.println("事务xid："+xid + "分支："+branchType.name());

        Order order = new Order();
        order.setUserId(userId);
        order.setItemId(itemId);
        order.setNum(num);
        orderRepository.save(order);

        // 扣除库存
        inventoryFeign.adjust(itemId, num);

        return "创建成功";
    }
}
